package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.tables.CustomerLatLngTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.ui.customers.CustomerEditActivity;
import com.gdk.ksoft.ui.customers.NewDeliverAddressActivity;
import com.gdk.ksoft.assembly.dialog.LocationRecorderDialog;
import com.gdk.ksoft.assembly.dialog.OperatorMenu;
import com.gdk.ksoft.assembly.utils.system.PhoneUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 客户详细信息页面
 */
public class CustomerDetailActivity extends Activity {

    @ViewInject(R.id.pcustomerDetail_llHeader)private LinearLayout llHeader;//顶部栏
    @ViewInject(R.id.item_fwork_lstcustomer_txtIcon)private TextView txtIcon;//客户类型图标
    @ViewInject(R.id.item_fwork_lstcustomer_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.item_fwork_lstcustomer_txtContactor)private TextView txtContactor;//客户联系人
    @ViewInject(R.id.item_fwork_lstcustomer_txtAddress)private TextView txtAddress;//客户联系地址
    @ViewInject(R.id.item_fwork_lstcustomer_txtContacts)private TextView txtContacts;//收货联系人
    @ViewInject(R.id.item_fwork_lstcustomer_txtDistace)private TextView txtDistance;//距离信息
    @ViewInject(R.id.pcustomerDetail_txtDebtCount)private TextView txtDebtCount;//欠单总张数
    @ViewInject(R.id.pcustomerDetail_txtDebtMoney)private TextView txtDebtMoney;//欠款总金额

    private OperatorMenu operTopMenu;//顶部菜单组件
    private int screenWidth = 0;//屏幕宽度

    public static final int REQ_CODE_EDIT_INFORMATION = 0x0001;//修改客户信息的修改码
    public int netCustomerId,netAddressId,localeAddressId;//客户ID,网络送货地址ID，本地送货地址ID
    private String customerPriceName,customerDeliverAddress;//客户价格名称,客户送货地址
    private int debtCount = 0;//欠款张数
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_detail);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        initOperTopMenu();//初始化顶部菜单
        screenWidth = PhoneUtils.getScreenInfo(this).widthPixels;//获取屏幕宽度
        Intent intent = getIntent();
        if(intent!=null){//获取上一个页面传递的数据值
            netCustomerId = intent.getIntExtra("netCustomerId",0);
            txtCustomerName.setText(intent.getStringExtra("customerName"));
            txtIcon.setText(intent.getStringExtra("customerType"));
            txtContactor.setText(intent.getStringExtra("customerContactor"));
            txtContacts.setText(intent.getStringExtra("receiverContactor"));
            customerDeliverAddress = intent.getStringExtra("receiverAddress");
            txtAddress.setText("地址："+customerDeliverAddress);
            netAddressId = intent.getIntExtra("netAddressId",0);
            localeAddressId = intent.getIntExtra("localeAddressId",0);
            customerPriceName = intent.getStringExtra("priceName");
            String latlng = intent.getStringExtra("latlng");
            if(!TextUtils.isEmpty(latlng) && SystemData.currentLocation!=null){//初始化计算的距离单位
                String[] latlngs = latlng.split(",");
                txtDistance.setText(FormatUtils.exactDistance(new LatLng(SystemData.currentLocation.getLatitude(),
                        SystemData.currentLocation.getLongitude()), new LatLng(Double.parseDouble(latlngs[0]), Double.parseDouble(latlngs[1]))));
            }else{
                txtDistance.setText("");
            }
        }
        txtDebtCount.post(new Runnable() {//执行查询欠款等信息
            @Override
            public void run() {
                try {
                    HashMap<String,Object> value = FworkDbHelper
                            .queryCustomerDebt(dbUtils, netCustomerId);
                    if(value != null){//查询成功的
                        debtCount = Integer.parseInt(value.get("debt").toString());
                        txtDebtCount.setText("欠款单数："+debtCount+"张");
                        txtDebtMoney.setText("欠款金额："+value.get("debtMoney")+"元");
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化顶部菜单
     */
    public void initOperTopMenu(){
        List<OperatorMenu.OperatorItem> list = new ArrayList<>();
        list.add(new OperatorMenu.OperatorItem(android.R.drawable.ic_menu_add,"添加收货地址"));
        list.add(new OperatorMenu.OperatorItem(android.R.drawable.ic_menu_edit,"修改客户资料"));
        operTopMenu = new OperatorMenu(this,list);
        operTopMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch(position){
                    case 0://添加收货地址
                        Intent addrIntent = new Intent(CustomerDetailActivity.this, NewDeliverAddressActivity.class);
                        addrIntent.putExtra("customerId",netCustomerId);
                        addrIntent.putExtra("customerName",txtCustomerName.getText().toString());
                        startActivity(addrIntent);
                        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                        break;
                    case 1://修改客户信息
//                        Toast.makeText(CustomerDetailActivity.this,"正在更新，敬请期待!",Toast.LENGTH_SHORT).show();
                        if(SystemData.IsOperatorCustomer == 1){
                            Intent intent = new Intent(CustomerDetailActivity.this, CustomerEditActivity.class);
                            intent.putExtra("customerId",netCustomerId);
                            intent.putExtra("addressId",netAddressId);
                            startActivityForResult(intent, REQ_CODE_EDIT_INFORMATION);
                            overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                        }else{
                            Toast.makeText(CustomerDetailActivity.this,"对不起，你没有权限进行操作!",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
                operTopMenu.dismiss();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(operTopMenu!=null){
            if(!operTopMenu.isShowing())
                operTopMenu.showAsDropDown(llHeader,screenWidth - ConstantData.TOP_MENU_WIDTH,0);
            else
                operTopMenu.dismiss();
        }
        return false;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        menu.add("");
        return super.onMenuOpened(featureId, menu);
    }

    @OnClick(value={R.id.pcustomerDetail_txtDebt,R.id.pcustomerDetail_txtPlaceOrder,
            R.id.pcustomerDetail_txtRecorderLoc,R.id.pcustomerDetail_imgMenu})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pcustomerDetail_txtDebt://收欠款
                if(debtCount <= 0){
                    Toast.makeText(this,"当前没有欠款可收取!",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(this, CustomerDebtActivity.class);
                intent.putExtra("customerName",txtCustomerName.getText().toString());//客户名称
                intent.putExtra("netCustomerId",netCustomerId);//客户网络ID
                intent.putExtra("netAddressId",netAddressId);//送货地址网络ID
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            case R.id.pcustomerDetail_txtPlaceOrder://开单
                Intent intentPlaceOrder = new Intent(this, PlaceOrderActivity.class);
                intentPlaceOrder.putExtra("customerName",txtCustomerName.getText().toString());//客户名称
                intentPlaceOrder.putExtra("netCustomerId",netCustomerId);//客户网络ID
                intentPlaceOrder.putExtra("netAddressId",netAddressId);//送货地址网络ID
                intentPlaceOrder.putExtra("priceName",customerPriceName);//传递客户价格名称
                startActivity(intentPlaceOrder);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.pcustomerDetail_txtRecorderLoc://校正位置
                adjustLatLng();//调整经纬度数据参数
                break;
            case R.id.pcustomerDetail_imgMenu://菜单按钮
                if(!operTopMenu.isShowing())
                    operTopMenu.showAsDropDown(llHeader,screenWidth - ConstantData.TOP_MENU_WIDTH,0);
                else
                    operTopMenu.dismiss();
                break;
        }
    }

    /**
     * 调整经纬度数据参数
     */
    public void adjustLatLng(){
        final LocationRecorderDialog dialog = new LocationRecorderDialog(this, txtCustomerName.getText().toString(),customerDeliverAddress);
        dialog.setOnPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.drecorder_location_txtCustomerOK://确定收录
                        SQLiteDatabase database = dbUtils.getDatabase();
                        try {
                            database.beginTransaction();
                            //修改本地存储的收货地址坐标
                            DeliverGoodsTable data = new DeliverGoodsTable();
                            data.djbz = 0;//标记为本地坐标（数据需要上传）
                            data.jwd = SystemData.currentLocation.getLatitude() + "," + SystemData.currentLocation.getLongitude();
                            dbUtils.update(data, WhereBuilder.b("kh_id", "=", netCustomerId), "jwd");
                            txtDistance.setText(FormatUtils.exactDistance(new LatLng(SystemData.currentLocation.getLatitude(),
                                    SystemData.currentLocation.getLongitude()), new LatLng(SystemData.currentLocation.getLatitude(),
                                    SystemData.currentLocation.getLongitude())));
                            CustomerLatLngTable clatlng = new CustomerLatLngTable();
                            clatlng.kh_id = netCustomerId;
                            clatlng.shdz_id = netAddressId;
                            clatlng.latlng = data.jwd;
                            clatlng.djbz = 0;//表示单机
                            dbUtils.save(clatlng);//存储经纬度到表
                            Toast.makeText(CustomerDetailActivity.this,"收录客户坐标成功!",Toast.LENGTH_SHORT).show();
                            database.setTransactionSuccessful();
                        }catch(Exception e){
                            e.printStackTrace();
                            Toast.makeText(CustomerDetailActivity.this,"收录客户坐标失败!",Toast.LENGTH_SHORT).show();
                        }
                        database.endTransaction();
                        break;
                    case R.id.drecorder_location_txtCustomerCancel://取消收录
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE_EDIT_INFORMATION && resultCode == Activity.RESULT_OK){//确认已经修改了客户信息
            if(data!=null){//返回的修改了的参数
                txtCustomerName.setText(data.getStringExtra("mc"));
                txtAddress.setText("地址："+data.getStringExtra("shdz"));
                txtContactor.setText(data.getStringExtra("lxr")+" "+data.getStringExtra("dh"));
                txtContacts.setText(data.getStringExtra("shr")+" "+data.getStringExtra("shdh"));
            }
        }
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pcustomerDetail_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
